const medicalService = require('../../../services/medical');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    petId: null,
    petName: '',
    vaccines: [],
    isLoading: true,
    hasError: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.petId) {
      this.setData({
        petId: options.petId
      });
      
      // 获取宠物名称
      const petInfo = wx.getStorageSync('currentPet');
      if (petInfo && petInfo.id == options.petId) {
        this.setData({
          petName: petInfo.name
        });
        wx.setNavigationBarTitle({
          title: `${petInfo.name}的疫苗记录`
        });
      }
      
      this.loadVaccineRecords();
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.petId) {
      this.loadVaccineRecords();
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadVaccineRecords();
  },

  /**
   * 加载疫苗记录
   */
  loadVaccineRecords() {
    this.setData({ 
      isLoading: true,
      hasError: false
    });
    
    medicalService.getVaccineRecords(this.data.petId)
      .then(res => {
        console.log('获取疫苗记录成功:', res);
        this.setData({
          vaccines: res || [],
          isLoading: false
        });
        wx.stopPullDownRefresh();
      })
      .catch(err => {
        console.error('获取疫苗记录失败', err);
        this.setData({ 
          isLoading: false,
          hasError: true,
          vaccines: []
        });
        wx.stopPullDownRefresh();
        wx.showToast({
          title: '获取疫苗记录失败',
          icon: 'none'
        });
      });
  },

  /**
   * 添加新的疫苗记录
   */
  navigateToAdd() {
    wx.navigateTo({
      url: `/pages/medical/vaccine/add?petId=${this.data.petId}`
    });
  }
}); 